﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using nelech.Models;
using nelech.Controllers;
using nelech.Models.DBModel;
using System.Net.Mail;
using System.Net;
using nelech.Controllers.Utils;
using nelech.Views.Shared.Code;
using nelech.Models.ContactModel;




namespace nelech.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        nelechDBEntities db = new nelechDBEntities();

       

        public ActionResult Index()
        {
            var lastTrack = db.Track.Where(p => p.publish == 1).OrderBy(p => p.number).AsEnumerable().Last();
            var lastSpring = db.Maayan.Where(p => p.publish == 1).OrderBy(p => p.id).AsEnumerable().Last();
            var lastPlace = db.Place.Where(p => p.publish == 1).OrderBy(p => p.id).AsEnumerable().Last();
            var placeRec = db.RecommendedPlace.ToList();
            var adverts = db.Advert.Where(p =>p.publish.HasValue && p.publish.Value == 1);
            int advertCount = Utils.AdvertControllerUtils.GetAdvertCount(2, null, db);
            var advertsArray =  Utils.AdvertControllerUtils.GetUniqueArray(advertCount);
            ViewData["advertsArray"] = advertsArray;
            ViewData["advertCount"] = advertsArray == null ? 0 : advertsArray.Length;
            var placeList = new List<Place>();
            foreach (var rec in placeRec)
            {
                var place = db.Place.First(p => p.id == rec.id);
                placeList.Add(place);
                place.Image.Load();
                PlaceController.LoadPlaceRelations(place);
            }
            var springRec = db.RecommendedSpring.ToList();
            var springList = new List<Maayan>();
            foreach (var rec in springRec)
            {
                var spring = db.Maayan.First(p => p.id == rec.id);
                springList.Add(spring);
                spring.Image.Load();
                PlaceController.LoadSpringRelations(spring);
            }
            ViewData["text"] = db.Text.First(p=> p.id == 3);  
            var trackRec = db.RecommendedTrack.ToList();
            var trackList = new List<Track>();
            foreach (var rec in trackRec)
            {
                var track = db.Track.First(p => p.number == rec.id);
                trackList.Add(track);
                track.Image.Load();
                TrackController.LoadTrackRelations(track);
            }

            db.SaveChanges();
              var array = new Object[6];
            array[0] = lastTrack;
            array[1] = lastSpring;
            array[2] = lastPlace;
            array[3] = placeList;
            array[4] = springList;
            array[5] = trackList;
           // array[6] = advertsPlaces;
            return View(array);
        }

        public ActionResult GetVisitorCounter()
        {
            return PartialView(db.See.First().see1);
        }

        public ActionResult Safety()
        {
            return View(db.Text.First(p => p.id == 1));
        }
        public ActionResult ListStuff()
        {
            return View("Safety", db.Text.First(p => p.id == 4));
        }
        public ActionResult HalachaTime()
        {
            return View("Safety", db.Text.First(p => p.id == 6));
        }
        public ActionResult Halacha()
        {
            return View("Safety", db.Text.First(p => p.id == 5));
        }
        public ActionResult IsraelMap(int id)
        {
            var list = new Object[4];
            var tracks = db.Track.Where(p => p.publish == 1 && p.Regeon1.id == id).AsEnumerable();
            tracks = tracks.OrderBy(p => p.number, new ReverseIntComparer());

            var places = db.Place.Where(p => p.publish == 1 && p.Regeon1.id == id).AsEnumerable();
            places = places.OrderBy(p => p.id, new ReverseIntComparer());

            var springs = db.Maayan.Where(p => p.publish == 1 && p.Regeon1.id == id).AsEnumerable();
            springs = springs.OrderBy(p => p.id, new ReverseIntComparer());

            var regeon = db.Regeon.First(p => p.id == id);

            foreach (var track in tracks)
            {
                TrackController.LoadTrackRelations(track);
            }


            foreach (var place in places)
            {
                PlaceController.LoadPlaceRelations(place);
            }
            foreach (var spring in springs)
            {
                PlaceController.LoadSpringRelations(spring);
            }
            list[0] = tracks;
            list[1] = places;
            list[2] = springs;
            list[3] = regeon;

            return View(list);

        }
        public ActionResult MunachInfo(int id)
        {
            return View(db.Munach.First(p => p.id == id));
        }
        public ActionResult ListMunach()
        {
            return View(db.Munach.Where(p => p.publish == 1));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SubmitContact(Contact contact)
        {
            if (!ModelState.IsValid)
                return View("Contact");
            string strTo;
            if (contact.subject == 0 || contact.subject == 1)
            {
                strTo = "editor@nelech.co.il";
            }
            else
            {
                strTo = "info@nelech.co.il";
            }
            string strFrom = "noreply@nelech.co.il";//form["email"];
            string strSubject = nelech.Views.Shared.Code.Utils.GetContactSubjectById(contact.subject);
            string strBody = string.Format(
                "name: {0}\nemail: {1} \ndescription: {2}",
                contact.name,
                contact.email,

                contact.description);

            SmtpClient smtpClient = new SmtpClient("Relay-Hosting.secureserver.net");

            smtpClient.Credentials = new NetworkCredential("noreply@nelech.co.il", "azaria1");
            smtpClient.Send(strFrom, strTo, strSubject, strBody);

            return View("Thanks");
        }
        public ActionResult Contact()
        {
            return View();
        }

        public ActionResult About()
        {
            return View(db.Text.First(p => p.id == 2));
        }
        public ActionResult Mishpatit()
        {
            return View(db.Text.First(p => p.id == 7));
        }
        [HttpPost]
        public ActionResult SearchFreeAll(string searchString)
        {
            if (string.IsNullOrEmpty(searchString))
            {
                return null;
            }
            var tracks = db.Track.Where(p => p.publish == 1).ToList();
            var springs = db.Maayan.Where(p => p.publish == 1).ToList();
            var places = db.Place.Where(p => p.publish == 1).ToList();
            var zimers = db.Zimer.Where(p => p.publish == 1).ToList();
            var munachs = db.Munach.Where(p => p.publish == 1).ToList();
            var texts = db.Text.ToList();
            tracks = SharedUtils.FreeSearchTrack(tracks, searchString);
            zimers = SharedUtils.FreeSearchZimer(zimers, searchString);
            springs = SharedUtils.FreeSearchSpring(springs, searchString).ToList();
            places = SharedUtils.FreeSearchPlace(places, searchString);
            munachs = SharedUtils.FreeSearchMunach(munachs, searchString);
            texts = SharedUtils.FreeSearchText(texts, searchString);
            var results = new SearchAll()
            {
                munachs = munachs,
                places = places,
                springs = springs,
                texts = texts,
                tracks = tracks,
                zimmers = zimers
            };

            return View(results);
        }

        public ActionResult AllList(int id)
        {
            var result = new SearchAll();
            switch (id)
            {
                case 1:
                default:
                   result.tracks = db.Track.Where(p => p.publish == 1).ToList();
                   break;
                case 2:
                   result.places = db.Place.Where(p => p.publish == 1).ToList();
                    break;
                case 3:
                    result.springs = db.Maayan.Where(p => p.publish == 1).ToList();
                    break;
                case 4:
                    result.zimmers = db.Zimer.Where(p => p.publish == 1).ToList();
                    break;
            }

            return View("SearchFreeAll", result);
        }

        public ActionResult MarqueeShow()
        {
            return PartialView(db.Marquee.ToList());
        }

        public ActionResult ListLinks()
        {
            return PartialView(db.Link.Where(p => p.publish == 1));
        }
        public ActionResult SpecialMap()
        {
           var places = db.Place.Where(p => p.publish == 1).ToList();
              var  tracks= db.Track.Where(p => p.publish == 1).ToList();
              var springs = db.Maayan.Where(p => p.publish == 1).ToList();
              var atrs = db.Attraction.Where(p => p.publish == true).ToList();
              foreach (var a in atrs)
              {
                  a.Image.Load();
                 
                  a.RegeonReference.Load();
              }
            foreach( var place in places)
            {
                place.Image.Load();
                place.Type.Load();
                place.Cost1Reference.Load();
                place.Regeon1Reference.Load();
            }
             foreach(var track in tracks)
            {
               
                track.Time1Reference.Load();
               
                
                track.Cost1Reference.Load();
                track.Difficulty1Reference.Load();
                track.Duration1Reference.Load();
                track.Season.Load();
                track.Regeon1Reference.Load();
                
            }
             foreach(var spring in springs)
            {
                spring.Cost1Reference.Load();
                spring.Image.Load();
                spring.Nevia1Reference.Load();
                spring.Regeon1Reference.Load();
            }
            var all = new SearchAll(){ places= places, springs = springs, tracks = tracks, attractions = atrs};
            return View(all);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SubmitContactUpdets(ContactUpdets contact)
        {
            if (!ModelState.IsValid)
                return RedirectToAction("Index");
           
          
            string strFrom = "noreply@nelech.co.il";//form["email"];
            string strSubject = "הוסף לרשימת עדכונים";
            string strBody = string.Format(
                "name: {0}\nemail: {1}",
                contact.name,
                contact.email);

            SmtpClient smtpClient = new SmtpClient("Relay-Hosting.secureserver.net");

            smtpClient.Credentials = new NetworkCredential("noreply@nelech.co.il", "azaria1");
            smtpClient.Send(strFrom, "editor@nelech.co.il", strSubject, strBody);

            return View("Thanks");
        }
      
    }
}
